package master;

import java.nio.channels.SeekableByteChannel;

/**
 * @author chenyw
 * @date 2022/8/13 14:51
 */
public class M190reverseBits {

    private static final int m1 = 0x55555555;  // 010101010101010101...
    private static final int m2 = 0x33333333;  // 0011001100110011...
    private static final int m3 = 0x0f0f0f0f;
    private static final int m4 = 0x00ff00ff;


    public int reverseBits(int n) {
        // | 相当于拼接， 有一个为1则为1
        n = n >>> 1 & m1 | (n & m1) << 1;
        n = n >>> 2 & m2 | (n & m2) << 2;
        n = n >>> 4 & m3 | (n & m3) << 4;
        n = n >>> 8 & m4 | (n & m4) << 8;
        return n >>> 16 | n << 16;
    }

/*    //遍历
    public int reverseBits(int n) {
        int res = 0;
        for (int i = 0; i < 32; i++) {
//            res += (n & 1) << (31 - i);
            res |= (n & 1) << (31 - i);
            n >>>= 1;
        }
        return res;
    }*/

}
